package main

import (
	"fmt"
	"net"
)

func test01() {
	fmt.Printf("服务器开始监听.........\n")
	listen, err := net.Listen("tcp", "0.0.0.0:8888")
	if err != nil {
		fmt.Printf("listen err ；%v \n", err)
		return
	}
	// Close closes the listener.
	// Any blocked Accept operations will be unblocked and return errors
	defer listen.Close()

	//loop waiting for client links
	for {
		//waiting for client links
		fmt.Printf("等待客户端链接........ \n")
		conn, err := listen.Accept() //blocked
		if err != nil {
			fmt.Printf("accept() err = %v \n", err)
		}
		//accept suc = &{{0xc0000c8080}} ,ip addr : 127.0.0.1:54258
		fmt.Printf("accept suc = %v ,ip addr : %v \n", conn, conn.RemoteAddr())
		//这里准备启动一个协程,来接受请求数据
		go process(conn)
	}

	fmt.Printf("listen suc = %v \n", listen) //listen suc = &{0xc0000c8000 {<nil> 0}}

}

func process(conn net.Conn) {

	//这里我们循环的介绍客户端发送的数据
	defer conn.Close() //关闭conn

	for {
		//创建一个新的slice
		buf := make([]byte, 1024)
		fmt.Printf("服务端等待客户端：%v ,发送信息 \n", conn.RemoteAddr().String())
		n, err := conn.Read(buf) //goroutine will blocked
		if err != nil {
			fmt.Printf("conn.read err = %v \n", err)
			return
		}
		//显示客户端发送的数据
		fmt.Printf("接受到的数据： %v \n", string(buf[:n]))

	}
}

func main() {
	test01()
}
